'use strict';

/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('essays', {
      id: {
        type: Sequelize.UUID,
        defaultValue: Sequelize.UUIDV4,
        primaryKey: true,
        allowNull: false,
        comment: '作文唯一标识',
      },
      user_id: {
        type: Sequelize.UUID,
        allowNull: false,
        references: {
          model: 'users',
          key: 'id',
        },
        onDelete: 'CASCADE',
        onUpdate: 'CASCADE',
        comment: '所属用户ID',
      },
      title: {
        type: Sequelize.STRING(200),
        allowNull: true,
        comment: '作文标题',
      },
      content: {
        type: Sequelize.TEXT,
        allowNull: false,
        comment: '作文内容',
      },
      image_url: {
        type: Sequelize.STRING(500),
        allowNull: true,
        comment: '作文图片URL（如果通过OCR提交）',
      },
      grade_level: {
        type: Sequelize.ENUM('primary', 'middle', 'high'),
        allowNull: false,
        comment: '年级层次：primary-小学，middle-初中，high-高中',
      },
      status: {
        type: Sequelize.ENUM('pending', 'processing', 'completed', 'failed'),
        defaultValue: 'pending',
        allowNull: false,
        comment: '批改状态',
      },
      score: {
        type: Sequelize.INTEGER,
        allowNull: true,
        validate: {
          min: 0,
          max: 100,
        },
        comment: 'AI批改评分（0-100分）',
      },
      correction_result: {
        type: Sequelize.JSON,
        allowNull: true,
        comment: 'AI批改结果（JSON格式）',
      },
      created_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
        comment: '创建时间',
      },
      updated_at: {
        type: Sequelize.DATE,
        allowNull: false,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'),
        comment: '更新时间',
      },
    }, {
      engine: 'InnoDB',
      charset: 'utf8mb4',
      collate: 'utf8mb4_unicode_ci',
      comment: '作文表',
    });

    // 创建索引
    await queryInterface.addIndex('essays', ['user_id'], {
      name: 'idx_user_id',
    });

    await queryInterface.addIndex('essays', ['status'], {
      name: 'idx_status',
    });

    await queryInterface.addIndex('essays', ['grade_level'], {
      name: 'idx_grade_level',
    });

    await queryInterface.addIndex('essays', ['created_at'], {
      name: 'idx_created_at',
    });

    await queryInterface.addIndex('essays', ['user_id', 'status'], {
      name: 'idx_user_status',
    });

    console.log('✅ Essays table created successfully');
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('essays');
    console.log('✅ Essays table dropped successfully');
  },
};

